package controller

import (
	"encoding/json"
	"gdfs-service/conf"
	"gdfs-service/constant"
	"gdfs-service/controller/ao"
	"gdfs-service/controller/vo"
	"gdfs-service/db"
	"gdfs-service/logcat"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
)

// @Summary 批量文件删除接口
// @Description 批量文件删除接口
// @Accept application/json
// @Param body body request.BatchDeleteRequest  true "要删除的批量文件秘钥"
// @Tags 文件上传下载接口
// @Success 200 {object} Result
// @Router /v1/batchDeleteFiles [post]
func BatchDeleteFile(c *gin.Context) {
	c.Writer.Header().Set("content-type", "application/json")
	result := vo.NewResultInstance()
	var rvo vo.BatchDeletVo
	var deleteao ao.BatchDeleteAo
	var fileinfos []db.FileInfo
	jsonerr := json.Unmarshal(GetPostJson(c.Request), &deleteao)
	if jsonerr != nil {
		result.Fail(constant.BussinessErrorType[constant.JSON_PARSE_ERROR], constant.JSON_PARSE_ERROR, rvo)
		WriteString(c.Writer, result)
		return
	}
	//查数据
	db.GetDB().Where("file_key in (?) AND deleted=?", deleteao.Filekeylist, "N").Find(&fileinfos)
	if fileinfos == nil {
		result.Fail(constant.BussinessErrorType[constant.NOTVALID_ERROR], constant.NOTVALID_ERROR, rvo)
		WriteString(c.Writer, result)
		return
	}
	var failist vo.Faillist
	var sucesslist vo.Sucesslist
	//遍历文件信息
	for _, fileinfo := range fileinfos {
		//filepath := fileinfo.FilePath + fileinfo.FileName
		s := strings.Split(fileinfo.FilePath, "/")
		filepath := conf.GetStorePath() + s[len(s)-2] + "/" + fileinfo.FilePath + "/" + fileinfo.FileName
		err := os.Remove(filepath)
		if err != nil {
			logcat.Info("批量删除失败", "key =", fileinfo.FileKey)
			//删除失败 在返回里面添加到失败列表
			var filekeyinfo vo.FilekeyInfo
			filekeyinfo.Filekey = fileinfo.FileKey
			filekeyinfo.Filename = fileinfo.FileName
			filekeyinfo.Filemessage = "删除失败"
			failist.Add(filekeyinfo)
		} else {
			logcat.Info("批量删除成功", "key =", fileinfo.FileKey)
			//删除成功更新数据库状态
			var filekeyinfo vo.FilekeyInfo
			filekeyinfo.Filekey = fileinfo.FileKey
			filekeyinfo.Filename = fileinfo.FileName
			filekeyinfo.Filemessage = "删除失败"
			db.GetDB().Delete(&fileinfo)
			sucesslist.Add(filekeyinfo)
		}
	}
	rvo.Sucesslist = sucesslist
	rvo.Faillist = failist
	result.SucessDefault(rvo)
	WriteString(c.Writer, result)
}

func GetPostJson(r *http.Request) []byte {
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		panic(err)
	}
	return body
}
